package com.gzz.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gzz.common.R;
import com.gzz.Dto.ZanDto;
import com.gzz.pojo.Comment;
import com.gzz.pojo.User;
import com.gzz.service.CommentService;
import com.gzz.service.UserService;
import com.gzz.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 */
@Slf4j
@RestController
@RequestMapping("/api/comment")
public class CommentController {

	@Autowired
	CommentService commentService;
	@Autowired
	UserService userService;
	@GetMapping("/list")
	public R<List<Comment>> getCommentList(@RequestParam(name = "stId") Long stId)
	{

		QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
		commentQueryWrapper.eq("st_id",stId);
		List<Comment> commentList = commentService.list(commentQueryWrapper);
		return R.success(commentList);

	}

	@PutMapping("/add")
	public R addComment(HttpServletRequest request, @RequestBody Comment comment)
	{
		String token = request.getHeader("token");
		Long id = JWTUtils.parseToken(token);
		User user = userService.getById(id);
		comment.setCommentTime(now());
		comment.setCommentZan(0L);
		comment.setUserId(id);
		comment.setTxImage(user.getUserAvatar());
		comment.setUserName(user.getUsername());
		log.info("内容为"+comment.getContent());
		commentService.save(comment);

		return R.success(true);
	}
	@PutMapping("/zan")
	public R addZan(@RequestBody ZanDto zanDto)
	{
		UpdateWrapper<Comment> commentUpdateWrapper = new UpdateWrapper<>();
		Comment comment = commentService.getById(zanDto.getId());
		Long num = comment.getCommentZan()+1;
		commentUpdateWrapper.eq("comment_id",zanDto.getId());
		commentUpdateWrapper.set("comment_zan",num);
		commentService.update(commentUpdateWrapper);
		return R.success(true);
	}
}

